# run.py 
# 
# Copyright 2011 Matt Whipple <matt@mattwhipple.com>
# 
# This file is part of com.teamsuperfitness.www
#
# com.teamsuperfitness.www is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your option)
# any later version.
# 
# com.teamsuperfitness.www is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
# 
# You should have received a copy of the GNU General Public License along
# with com.teamsuperfitness.www. If not, see http://www.gnu.org/licenses/.
#


# Needed to load libraries from subdirectories
import fix_path

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from models.WebLead import WebLead
import models
from tmpl import render_template

import formencode
from formencode import htmlfill
import api;
            
from google.appengine.api import mail

def render_path(clazz):
    """Pulls path information out of present handler"""
    clazz.response.headers['Content-Type'] = 'text/html'

    path = clazz.request.path
    if path == "/":
        path = "index.html"
    path = path[0:path.find(".")]
    return render_template(path)


class FormHandler(webapp.RequestHandler):
    """Basic form handler that handles validation"""
    defaults = {}
    schema = None
    redirect_to = "/"
    domain_object = None
    def pre_redirect(self):
        pass
    def get(self):
        self.response.out.write(htmlfill.render(render_path(self), self.defaults))

    def post(self):
        try:
            self.domain_object = self.schema.to_python(self.request.str_POST)
        except formencode.Invalid, e:
            string = render_path(self)
            return self.response.out.write(htmlfill.render(string, self.request.str_POST, e.error_dict or {}))
        self.pre_redirect()
        self.redirect(self.redirect_to)

class ContactForm(FormHandler):
    schema = models.Contact
    redirect_to = "/signup_sent.html"
    def pre_redirect(self):
        mail.send_mail(sender = "admin@teamsuperfitness.com",
                       to="info@teamsuperfitness.com",
                       subject="Web Site Contact Form",
                       body=render_template('mail/contact', {"contact": self.domain_object}))

class HandleSignup(FormHandler):
    schema = WebLead
    redirect_to = "/signup_sent.html"
    def pre_redirect(self):
        if self.domain_object['club'] == "Quincy":
            to_address = "quincy@teamsuperfitness.com"
        elif self.domain_object['club'] == "Watertown":
            to_address = "watertown@teamsuperfitness.com"
        mail.send_mail(sender="admin@teamsuperfitness.com",
                       to=to_address,
                       subject="Web Site Sign-Up",
                       body=render_template('mail/web_lead', {"lead": self.domain_object}))

class QuincyHandler(HandleSignup):
    defaults = {
        "club": "Quincy" }

class WatertownHandler(HandleSignup):
    defaults = {
        "club": "Watertown" }
    
class PathToTemplate(webapp.RequestHandler):
    def get(self):
        self.response.out.write(render_path(self))

application = webapp.WSGIApplication(
    [
        ('/rest/locations/quincy.json', api.QuincyInfo),
        ('/rest/locations/watertown.json', api.WatertownInfo),
        ('/rest/loginInfo.json', api.LoginInfo),
        ('/login', api.LoginPage),
        ('/land/freegympass.html', HandleSignup),
        ('/pageContent/land/freegympass.html', HandleSignup),
        ('/land/watertown.html', WatertownHandler),
        ('/land/watertownt.html', WatertownHandler),
        ('/land/quincy.html', QuincyHandler),
        ('/contact.html', ContactForm),
        ('/.*', PathToTemplate),
        ],
    debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
